package com.wxl.common.wiget

import android.content.Context
import android.text.TextUtils
import android.view.KeyEvent
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.CenterPopupView
import com.wxl.common.AppContext
import com.wxl.common.R
import com.wxl.common.base.AbsActivity
import com.wxl.common.serialport.SerialPortManager
import kotlinx.android.synthetic.main.pop_shot_circuit_layout.view.*


/**
 * 短路提示
 */
class SerialControlShotCircuitPop : CenterPopupView{

    private var content:String? = null

    constructor(context: Context) : super(context)

    override fun getImplLayoutId(): Int {
        return R.layout.pop_shot_circuit_layout
    }


    override fun onCreate() {
        super.onCreate()
        if(!TextUtils.isEmpty(content)){
            shortCircuitContent.text = content
        }
        shortCircuitCancel.setOnClickListener {
            dismiss()
            exitTaskTopPage()
        }

        shortCircuitSure.setOnClickListener {
            dismiss()
            SerialPortManager.clearOutSerialPort(null)
            exitTaskTopPage()
        }
    }

    /**
     * 退出当前页
     */
    private fun exitTaskTopPage(){
        val activity = AppContext.appContext.getCurrentActivity()
        if(activity != null && !TextUtils.equals("com.blast.manager.ui.ManagerMainActivity",activity::class.java.name)){
            activity.finish()
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if(keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_F1){
            shortCircuitCancel.performClick()
        } else if(keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_F4){
            shortCircuitSure.performClick()
        }
        return true
    }

    companion object {
        fun show(context: Context?){
            context?.let {
                (context as AbsActivity).addPop(
                XPopup.Builder(context)
                    .dismissOnTouchOutside(false)
                    .asCustom(SerialControlShotCircuitPop(context))
                    .show()
                )
            }
        }
    }
}